/**
 * Created by ztt on 2017/11/17.
 */
const express = require('express');
const app = express();
const fs = require("fs");

/**
 * todo:跨域处理
 */
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

//浏览器通过这种形式的url访问localhost/userlist?id=xxx&name=yyy，这种方式可以通过req.query.id获取参数的值
app.get('/organization/unique/:name', function(req, res, next) {
    let flag = Math.random()>0.5;
    let message = "请求接口成功！";
    if(flag){
        //res.redirect('http://10.10.60.10:8080/user/login.html');
        res.status(401);
        res.set({'redirectTo':'http://10.10.39.10:8080/user/login.html'});
        message = '用户未登录或session已过期！';
    }
    let serviceRequestFlag = req.get('service-request-flag');
    console.log('\nserviceRequestFlag:',serviceRequestFlag);
    console.log('req.headers:',req.headers);
    let name = req.params.name;
    let result={"result":flag,"success":flag,"message":message};
    console.log(`${name}`,result);
    res.send(result);
});
//浏览器通过这种形式的url访问localhost/userlist?id=xxx&name=yyy，这种方式可以通过req.query.id获取参数的值
app.post('/organization/unique/:name', function(req, res, next) {
    let flag = Math.random()>0.5;
    let message = "请求接口成功！";
    if(flag){
        //res.redirect('http://10.10.60.10:8080/user/login.html');
        res.status(401);
        res.set({'redirectTo':'http://10.10.39.10:8080/user/login.html'});
        message = '用户未登录或session已过期！';
    }
    let serviceRequestFlag = req.get('service-request-flag');
    console.log('\nserviceRequestFlag:',serviceRequestFlag);
    console.log('req.headers:',req.headers);
    let name = req.params.name;
    let result={"result":flag,"success":flag,"message":message};
    console.log(`${name}`,result);
    res.send(result);
});

app.get('/user/unique/:id',function (req,res) {
    let flag = Math.random()>0.5;
    if(flag){
        res.setState(401);
        res.setItem('redirectUrl','http://10.10.39.10:8080/user/login.html');
        res.setHeaders('redirectUrl','http://10.10.39.10:8080/user/login.html');
    }
    fs.readFile(__dirname+"/"+"users.json",'utf-8',function (err,data) {
        data=JSON.parse(data);
        var user=data["user"+req.params.id];
        let result={"result":flag,"success":flag,"message":flag?"编码已存在！":'编码不存在'};
        res.send(true);
    });
});

var server = app.listen(3000, function () {
    var host = server.address().address
    var port = server.address().port
    console.log("应用实例，访问地址为 http://%s:%s", host, port)
});
